package what.the.fun.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import what.the.fun.domain.Question;
import what.the.fun.jdbc.QuestionRowMapper;

public class QuestionDAOImpl implements QuestionDAO{

	@Autowired
	DataSource dataSource;
	JdbcTemplate jdbcTemplate;
	String sql;
	
	@Override
	public List<Question> getDataList() {
		sql = "call sp_question_GetAll ()";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Question> list = new ArrayList<Question>();
		list = jdbcTemplate.query(sql, new QuestionRowMapper());
		
		return list;
	}

	@Override
	public void insertData(Question data) {
		sql = "call sp_question_Insert (?, ?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, data.getQuestContent(), data.getSurveyId(), data.getLimitAnswer());
	}

	@Override
	public void updateData(Question data) {
		sql = "call sp_question_Update (?, ?, ?, ?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, data.getQuestContent(), data.getSurveyId(), data.getQuestId(), data.getLimitAnswer());
	}

	@Override
	public void deleteData(String id) {
		sql = "call sp_question_Delete (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		jdbcTemplate.update(sql, id);
	}

	@Override
	public Question getData(String id) {
		sql = "call sp_question_GetById (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Question> list = new ArrayList<Question>();
		list = jdbcTemplate.query(sql, new QuestionRowMapper(), id);
		
		return list.get(0);
	}

	@Override
	public List<Question> getQuestionListBySurveyId(String surveyId) {
		sql = "call sp_question_GetQuestionListBySurveyId (?)";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Question> list = new ArrayList<Question>();
		list = jdbcTemplate.query(sql, new QuestionRowMapper(), surveyId);
		
		return list;
	}

	@Override
	public Question getLast() {
		sql = "call sp_question_GetLast ()";
		jdbcTemplate = new JdbcTemplate(dataSource);
		
		List<Question> list = new ArrayList<Question>();
		list = jdbcTemplate.query(sql, new QuestionRowMapper());
		
		return list.get(0);
	}

}
